package com.lzq.mq.broker.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;

/**
 * 文件处理工具类
 */
public class FileContentUtil {

    /**
     * 读取文件所有内容,以String形式返回
     * @param path 文件绝对路径
     * @return 文件内容
     */
    public static String readFromFile(String path) {

        try (BufferedReader in = new BufferedReader(new FileReader(path))) {
            // try-source会自动关闭io,不需要手动关闭!
            StringBuffer stb = new StringBuffer();
            while (in.ready()) {
                stb.append(in.readLine());
            }
            return stb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 覆盖写入文件
     * @param path 文件绝对路径
     * @param content 内容
     */
    public static void overWriteToFile(String path, String content) {
        try (FileWriter fileWriter = new FileWriter(path);) {

            fileWriter.write(content);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
